package com.mu.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mu.common.Constants;
import com.mu.entity.Record2023;
import com.mu.entity.Record2024;
import com.mu.entity.User;
import com.mu.exception.ServiceException;
import com.mu.mapper.Records2023Mapper;
import com.mu.mapper.Records2024Mapper;
import com.mu.service.Records2023Service;
import com.mu.service.Records2024Service;
import com.mu.service.UserService;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mu
 * @since 2022-10-25
 */
@Service
public class Records2024ServiceImpl extends ServiceImpl<Records2024Mapper, Record2024> implements Records2024Service {

    @Resource
    private UserService userService;

    @Resource
    private DataSourceTransactionManager metaTransactionManager;

    @Override
    public Record2024 getByAccount(String account) {
        QueryWrapper<Record2024> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("学籍号",account);
        Record2024 one ;
        try {
            one = getOne(queryWrapper);//从数据库查询用户信息
            //数据库查询，可以视为系统异常
            System.out.println(one);
        } catch (Exception e) {
            log.error(String.valueOf(e));
            throw new ServiceException(Constants.CODE_500,"系统错误");//如果有多条数据，返回false
        }
        return one;
    }

    @Override
    public void imp(MultipartFile file, String schoolYear) throws IOException {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务，这样会比较安全些。

        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //List<Record> list = reader.readAll(Record.class);

        //方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Record2024> records = CollUtil.newArrayList();
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            Record2024 record = new Record2024();
            User user = new User(); //用来更新user表数据
            record.setCollege(row.get(0).toString());
            record.setCls(row.get(1).toString());
            user.setCollage(row.get(0).toString());
            user.setCls(row.get(1).toString());
            record.setAccount(row.get(2).toString());//学籍号
            record.setName(row.get(3).toString());//姓名
            //用户表信息
            user.setAccount(row.get(2).toString());
            user.setPassword(row.get(2).toString());
            user.setName(row.get(3).toString());
            user.setRole("学生");

            record.setSex(row.get(4).toString());
            record.setHeight(Double.valueOf(row.get(5).toString()));
            record.setWeight(Double.valueOf(row.get(6).toString()));
            record.setHeightAndWeightScore(row.get(7).toString());
            record.setHeightAndWeightLevel(row.get(8).toString());
            record.setVitalCapacity(Integer.valueOf(row.get(9).toString()));
            record.setVitalCapacityBodyMassScore(Integer.valueOf(row.get(10).toString()));
            record.setVitalCapacityWeightLevel(row.get(11).toString());
            record.setFiftyRun(Double.valueOf(row.get(12).toString()));
            record.setFiftyRunScore(Integer.valueOf(row.get(13).toString()));
            record.setFiftyRunLevel(row.get(14).toString());
            record.setThousandRun(row.get(15).toString());
            record.setThousandRunScore(Integer.valueOf(row.get(16).toString()));
            record.setThousandRunLevel(row.get(17).toString());
            record.setSittingForwardFlexion(Double.valueOf(row.get(18).toString()));
            record.setSittingForwardFlexionScore(Integer.valueOf(row.get(19).toString()));
            record.setSittingForwardFlexionLevel(row.get(20).toString());
            record.setStandingLongJump(Integer.valueOf(row.get(21).toString()));
            record.setStandingLongJumpScore(Integer.valueOf(row.get(22).toString()));
            record.setStandingLongJumpLevel(row.get(23).toString());
            record.setPullUpOrOneMinuteSitUps(Integer.valueOf(row.get(24).toString()));
            record.setPullUpOrOneMinuteSitUpsScore(Integer.valueOf(row.get(25).toString()));
            record.setPullUpOrOneMinuteSitUpsLevel(row.get(26).toString());
            record.setTotalTestScore(Integer.valueOf(row.get(27).toString()));
            record.setTotalTestLevel(row.get(28).toString());
            records.add(record);
            users.add(user);
        }

        TransactionStatus status = metaTransactionManager.getTransaction(def);

        try {
            for (Record2024 res : records) {
                QueryWrapper<Record2024> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("学籍号", res.getAccount());
                Record2024 findOne  = getOne(queryWrapper);
                if (findOne != null) {
                    update(res,queryWrapper);
                } else {
                    save(res);
                }
            }
            for (User user : users) {
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("account", user.getAccount());
                User findOne  = userService.getOne(queryWrapper);
                if (findOne != null) {
                    userService.update(user,queryWrapper);
                } else {
                    userService.save(user);
                }
            }
            //手动事务提交
            metaTransactionManager.commit(status);
        } catch (Exception e) {
            //手动开启事务回滚
            metaTransactionManager.rollback(status);
            //可以添加错误日志
            System.out.println("出错了,插入失败");
        }

    }



    @Override
    public Boolean saveOrUpd(Record2024 record) {
        QueryWrapper<Record2024> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("学籍号", record.getAccount());
        Record2024 findOne = getOne(queryWrapper);
        if (findOne != null) {
            update(record,queryWrapper);
        } else {
            save(record);
        }
        User findUser = userService.findOneByAccount(record.getAccount());
        if (findUser == null) {
            User user = new User();
            user.setAccount(record.getAccount());
            user.setName(record.getName());
            user.setPassword(record.getAccount());
            userService.save(user);
        }
        return true;
    }

}
